// __PUBLIC__/js/page/admin/global/email
require(['../../common'], function() {
  require(['global.email'])
})

define('global.email', [
  'jquery',
  'jqp/validate'
], function($) {
  'use strict';

  // TODO: 应该 ajax 获取
  var smtps = [{
    addr: 'smtp.126.com',
    port: 25,
    ssl: false
  }, {
    addr: 'smtp.163.com',
    port: 25,
    ssl: false
  }, {
    addr: 'smtp.gmail.com',
    port: 465,
    ssl: true
  }, {
    addr: 'smtp.hotmail.com',
    port: 25,
    ssl: true
  }, {
    addr: 'smtp.qq.com',
    port: 25,
    ssl: true
  }, {
    addr: 'smtp.sina.com',
    port: 25,
    ssl: false
  }, {
    addr: 'smtp.mail.yahoo.com',
    port: 465,
    ssl: true
  }, {
    addr: 'other',
    port: '',
    ssl: false
  }]

  var $smtps = $('#J_smtps')
  var selectedSmtp = $smtps.data('value')
  var options = ''
  $.each(smtps, function() {
    var addr = this.addr
    options += '<option value="' + addr + '"' +
      (addr === selectedSmtp ? ' selected>' : '>') + addr + '</option>'
  })
  $smtps.html(options)
    .on('change', function() {
      var val = this.value
      var obj

      if (val === 'other') {
        $('#email_host').show()
        obj = {
          port: 25, // 通常是 25
          ssl: false
        }
      } else {
        $('#email_host').hide()
        for (var i = 0, len = smtps.length; i < len; i++) {
          if (smtps[i].addr === val) {
            obj = {
              port: smtps[i].port,
              ssl: smtps[i].ssl
            }
            break
          }
        }
      }

      if (obj.ssl) {
        $('#email_ssl_1').click()
        $('#email_ssl_encrypt').val('ssl')
      } else {
        $('#email_ssl_encrypt').val('')
        $('#email_ssl_0').click()
      }
      $('#email_port').val(obj.port)

    })

  var $form = $('#J_form').validate({
    classPlace: '.kv',
    errorPlace: '.kv-error',
    errors: {
      'email_account': {
        email: lang.emailFormatErrors
      },
      'testSendEmailTo': {
        email: lang.emailFormatErrors
      }
    }
  })

  var validator = $form.data('validator')

  // TODO: 确定 email_account 是否必填
  $('#J_type').on('change', function() {
    if (this.value === 'smtp') {
      $('#J_smtpSettings').show()
      // validator.errors['email_account'].required = '请填写邮箱'
    } else {
      $('#J_smtpSettings').hide()
      // delete validator.errors['email_account'].required
    }
  })

  // 测试发送邮件
  $('#J_send').on('click', function(e) {
    var field = document.getElementById('testSendEmailTo')
    var valid = validator.validateField.call(validator, field, {
      required: '请填写邮箱',
      email: lang.emailFormatErrors
    })

    if (!valid) {
      return false
    }

    e.preventDefault()
    $.post(APP + '?app=admin&m=Global&a=testSendEmail', {
      testSendEmailTo: $.trim(field.value)
    })
      .done(function(res) {
        if (res == 1) {
          alert(lang.emailSended)
        } else {
          alert(res)
        }
      })
  })
})
